package com.usermanage.controller;

import com.usermanage.SecurityConfig.SpringSecurityUtils;
import com.usermanage.SecurityConfig.UserDetail;
import com.usermanage.Service.GroupMemberService;
import com.usermanage.Service.GroupPermissionService;
import com.usermanage.Service.GroupService;
import com.usermanage.Service.PermissionService;
import com.usermanage.beanParam.*;
import com.usermanage.util.JsonData;
import com.usermanage.util.StaticUtil;
import com.usermanage.util.StringUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import java.util.*;

@Slf4j
@RestController
@RequestMapping("/role")
public class RoleController {
    @Resource
    private GroupService groupService;

    @Resource
    private GroupMemberService groupMemberService;

    @Resource
    private PermissionService permissionService;

    @Resource
    private GroupPermissionService groupPermissionService;

    /**
     * 角色管理首页
     * @return
     * @throws Exception
     */
    @RequestMapping(value="/list.page",method= RequestMethod.GET)
    public ModelAndView roleListPage()throws Exception{
        ModelAndView mv = new ModelAndView();
        //获得用户登陆信息
        UserDetail userDetail = SpringSecurityUtils.getCurrentUser();
        //从用户登陆信息中获取用户权限列表
        List<PermissionBean> permissionBeanList = userDetail.getList();
        //判断用户具有的权限在界面展示
        List<PermissionBean> result = new ArrayList<>();
        for (PermissionBean bean:permissionBeanList) {
            if (bean.getPermission_url().equals("/role/add.page")){
                result.add(bean);
            }
        }
        mv.addObject("permissionList",result);
        mv.setViewName("/role/list");
        return mv;
    }

    /**
     * 分页，条件查询，获得角色列表
     * @param key
     * @param page
     * @param size
     * @return
     * @throws Exception
     */
    @RequestMapping(value="/list.json",method= RequestMethod.POST)
    public JsonData roleListJson(String key, String page, String size)throws Exception{

        if (StringUtils.isBlank(page)){
            page = StaticUtil.pageIndex;
        }
        if (StringUtils.isBlank(size)){
            size = StaticUtil.sizeCount;
        }
        //根据用户组的uuid得到用户的角色列表
        List<GroupBean> list =groupService.getAllByCompanyId(key,page,size);
        //根据用户组的uuid得到用户的角色列表记录数
        int count = groupService.getAllCountByGroupUuid(key);
        //从用户信息中获取权限列表，此处拼接列表的权限button按钮
        List<PermissionBean> permissionBeanList = SpringSecurityUtils.getCurrentUser().getList();
        List<Map> operaButton = new ArrayList<>();
        for (PermissionBean bean:permissionBeanList) {
            if (bean.getPermission_url().equals("/role/del.json")){
                Map map = new HashMap();
                map.put("name",bean.getPermission_name());
                map.put("fn","del");
                operaButton.add(map);
            }
            if (bean.getPermission_url().equals("/role/detail.page")){
                Map map = new HashMap();
                map.put("name",bean.getPermission_name());
                map.put("fn","detail");
                operaButton.add(map);
            }
        }
        if (StringUtils.isBlank(key)){
            key="''";
        }
        if (operaButton.size()==0){
            Map map = new HashMap();
            map.put("name","--");
            operaButton.add(map);
        }
        Map resultMap = new HashMap();
        resultMap.put("list",list);
        resultMap.put("total",count == 0 ? 1:count);
        resultMap.put("operaButton",operaButton);
        resultMap.put("key",key);
        resultMap.put("pageIndex",page);
        resultMap.put("size",size);
        return JsonData.success(resultMap);
    }



    @RequestMapping(value="/select.json")
    public JsonData roleListJson()throws Exception{
        String companyId = SpringSecurityUtils.getCurrentUser().getCompany_id();
        GroupBean bean = new GroupBean();
        bean.setCompany_id(companyId);
        List<GroupBean> list = groupService.findAllForSelect(bean);
        return JsonData.success(list);
    }
    /**
     * 添加角色界面
     * @return
     * @throws Exception
     */
    @RequestMapping(value="/add.page",method= RequestMethod.GET)
    public ModelAndView roleAddPage()throws Exception{
        ModelAndView mv = new ModelAndView();
        mv.setViewName("/role/add");
        return mv;
    }

    /**
     * 添加角色
     * @param name
     * @param tree
     * @return
     * @throws Exception
     */
    @RequestMapping(value="/add.json",method= RequestMethod.POST)
//    @Transactional
    public JsonData roleAdd(String name,String tree)throws Exception{
        if (StringUtils.isBlank(name)){
            return JsonData.fail("名字不能为空");
        }
        if (StringUtils.isBlank(tree)){
            return JsonData.fail("请选择权限");
        }
        GroupBean bean = new GroupBean();
        bean.setGroup_name(name);
        UserDetail userDetail = SpringSecurityUtils.getCurrentUser();
        bean.setCompany_id(userDetail.getCompany_id());
        //根据名字验证该权限组是否存在
        boolean bool = groupService.isExist(bean);
        if(bool){
            return JsonData.fail("该权限组已存在");
        }
        bean.setCreat_time(new Date());
        bean.setGroup_state("11");
        bean.setGroup_type("11");
        bean.setGroup_desc(name);
        //添加角色
        GroupBean resultBean = groupService.save(bean);
        //表示角色添加失败
        if (resultBean.getId()<=0){
            return JsonData.fail("添加失败，系统异常！");
        }
        //切分权限id
        String [] ids = tree.split(",");
        //遍历插入角色和权限绑定
        for (int i = 0;i<ids.length;i++){
            GroupPermissionBean groupPermissionBean = new GroupPermissionBean();
            groupPermissionBean.setPermission_id(ids[i]);
            groupPermissionBean.setGroup_id(String.valueOf(resultBean.getId()));
            //验证是否意境存在绑定
            boolean boolResult = groupPermissionService.isExsit(groupPermissionBean);
            if (!boolResult){
                groupPermissionService.save(groupPermissionBean);//为添加的角色绑定权限
            }
        }
        //添加角色组和权限的关系表
        return JsonData.success();
    }


    /**
     * 角色详情页面
     * @param id  角色id
     * @return
     * @throws Exception
     */
    @RequestMapping(value="/detail.page",method= RequestMethod.GET)
    public ModelAndView roleDetail(int id)throws Exception{
        ModelAndView mv = new ModelAndView();
        //获得组详情
        Optional<GroupBean> optional = groupService.findById(id);
        //得到角色组详情
        GroupBean groupBean = optional.get();
        GroupPermissionBean bean = new GroupPermissionBean();
        bean.setGroup_id(String.valueOf(id));
//        List<GroupPermissionBean> list = groupPermissionService.findAll(bean);
        //根据组id查看组下已具有的权限列表
        String str = permissionService.findPermissionEndListByGroupId(String.valueOf(id));
        String groupId = SpringSecurityUtils.getCurrentUser().getGroup_id();
        //登陆管理员具有的权限列表
        List<PermissionBean> permissionList = permissionService.findPermissionByGroupId(groupId);
        //得到登陆用户权限集合，判断用户是否有修改权限
        List<PermissionBean> permissionBeanList = SpringSecurityUtils.getCurrentUser().getList();
        String success = "fail";//没有修改权限
        for (PermissionBean permissionBean:permissionBeanList) {
            if (permissionBean.getPermission_url().equals("/role/update.json")){
                success = "success";//有修改权限
                break;
            }
        }
        mv.addObject("list",StringUtil.ObjectToJson(permissionList));
        mv.addObject("id",id);
        mv.addObject("name",groupBean.getGroup_name());
        mv.addObject("result",str);
        mv.addObject("success",success);
        mv.setViewName("/role/detail");
        return mv;
    }


    @RequestMapping(value="/update.json",method= RequestMethod.POST)
    public JsonData updateRole(String id,String tree,String name)throws Exception{
        if (StringUtils.isBlank(id)){
            return JsonData.fail("名字不能为空");
        }
        if (StringUtils.isBlank(tree)){
            return JsonData.fail("请选择权限");
        }
        Optional<GroupBean> optional = groupService.findById(Integer.valueOf(id));
        if (optional.isPresent()){
            GroupBean bean = optional.get();
            bean.setGroup_name(name);
            bean.setGroup_desc(name);
            groupService.save(bean);
        }
        GroupPermissionBean bean = new GroupPermissionBean();
        bean.setGroup_id(id);
        List<GroupPermissionBean> list = groupPermissionService.findAll(bean);
        for (GroupPermissionBean delBean:list) {
            groupPermissionService.delete(delBean);
        }
        String [] ids = tree.split(",");

        for (int i = 0;i<ids.length;i++){
            GroupPermissionBean addBean = new GroupPermissionBean();
            addBean.setGroup_id(id);
            addBean.setPermission_id(ids[i]);
            //为组添加新得权限数据
            groupPermissionService.save(addBean);
        }

//        SpringSecurityUtils.getCurrentUser().setList(permissionService.findPermissionByGroupId(id));
        return JsonData.success();
    }

    @RequestMapping(value="/del.json")
    public JsonData del(int id)throws Exception{
        UserDetail userDetail = SpringSecurityUtils.getCurrentUser();
        //验证该角色组是否被使用
        GroupMemberBean checkBean = new GroupMemberBean();
        checkBean.setGroup_id(String.valueOf(id));
        checkBean.setCompany_id(userDetail.getCompany_id());
        boolean bool = groupMemberService.isExist(checkBean);
        if (bool){
            return JsonData.fail("角色已被绑定使用，无法删除！");
        }
        Optional<GroupBean> optional = groupService.findById(id);
        if ("44".equals(optional.get().getGroup_type())){
            return JsonData.fail("基础角色，无法删除！");
        }
        groupService.deleteById(id);
        GroupPermissionBean groupPermissionBean = new GroupPermissionBean();
        groupPermissionBean.setGroup_id(String.valueOf(id));
        List<GroupPermissionBean> list = groupPermissionService.findAll(groupPermissionBean);
        for (GroupPermissionBean delBean:list) {
            groupPermissionService.deleteById(delBean.getId());
        }
        return JsonData.success();
    }

}
